<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/18/018
 * Time: 15:52
 * Author: wanghu
 */

namespace app\backend\controller;


use think\Controller;
use think\Db;
use think\Request;

/**
 * 用户控制器
 *
 * Class User
 * @package app\backend\controller
 * author : wanghu
 */
class User extends Controller
{
    /**
     * 显示用户登录页面以及执行登录操作
     *
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * author : wanghu
     */
    public function login()
    {
        if ($_POST) {
            $data = Request::instance()->post();
            $user_name = $data['user_name'];
            $salt = Db::table('user')->field('salt')->where('user_name', $user_name)->find();
            $user_pass = crypt($data['user_pass'], $salt['salt']);
            if (captcha_check($data['captcha'])) {
                $res = Db::table('user')->where(['user_name' => $user_name, 'password' => $user_pass])->find();
                if ($res) {
                    session('uid', $res['id']);
                    $this->success('登录成功', '/backend/index/index');
                } else {
                    $this->error('登录失败,用户名或密码不正确');
                }
            } else {
                $this->error('登录失败,验证码不正确');
            }
        } else {
            return view('login');
        }
    }

    /**
     * 显示用户信息列表
     *
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * author : wanghu
     */
    public function user_list()
    {
        $data = Db::table('user')->select();
        foreach ($data as $key=>$value) {
            $data[$key]['last_login_time'] = date('Y-m-d H:i:s', $value['last_login_time']);
            $data[$key]['last_login_ip'] = long2ip($value['last_login_ip']);
            $data[$key]['sex'] = $value['sex'] == 0 ? '男' : '女';
            $data[$key]['user_status'] = $value['user_status'] == 0 ? '启用' : '禁用';
        }
        $this->assign('data', $data);
        return view('user_list');
    }

    public function register()
    {
        $user_name = 'admin';
        $user_pass = '123456';
        $salt = 'waimaiApp';
        $res = Db::table('user')->insert([
            'user_name' => $user_name,
            'password' => crypt($user_pass, $salt),
            'salt' => $salt
        ]);
        return $res;
    }

    public function update()
    {
        $res = Db::table('user')->where('id', 1)->update(
            ['last_login_time' => time(), 'last_login_ip' => ip2long('127.0.0.1')]);
        return $res;
    }


}